<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Option;
use App\Models\Commission;
//use App\Models\UserRelationship;
use App\User;
use Validator,Config;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; 
use App\Repositories\MemberRepositoryEloquent;
class OrderController extends Controller{

    protected $user;

    public function __construct(MemberRepositoryEloquent $user)
    {
        //parent::__construct();
        $this->user = $user;

    }

    public function index($symbol){
        $option = Option::select('id','name', 'code','times')->where('code','=',$symbol)->first();
        //get_option_data('PMAU');
        $times = $option->times;
        
        $times = explode(',',$times);
        $newtimes = [];
        foreach($times as $k=>$time){
            list($start,$end) = explode('-',$time);
            if($start>=$end){
                //echo 1;
                $periodone = $start.'-24:00';
                $periodtwo = "00:00-".$end;
                //unset($times[$k]);
                $newtimes[] = $periodone;
                $newtimes[] = $periodtwo;
            }else{
                //echo 2;
                $newtimes[] = $time;
            }
        }
        //$times =implode(',',$times);
        $newtimes = json_encode($newtimes);
      //var_dump($newtimes);
        $optionData= get_option_data($symbol);
        //var_dump($optionData);
        return view('home.option.index',compact('option','newtimes','optionData'));
    }

    public function insert(Request $request){
        
        $user = $request->user();

        $validator = Validator::make($request->all(), [
            'option_id' => 'required|integer',
            'amount'=>'required|numeric|min:0.01',
            'direction'=>'required|integer',
            'buy_point'=>'required|numeric',
            'times'=>'required|integer',
            'yield_rate'=>'required|numeric',
        ]);
        $option_id = $request->option_id;
        $option = Option::select('id','name', 'code','times')->where('id','=',$option_id)->first();
        //var_dump($option);
        $optionData = get_option_data($option->code);
        //var_dump($optionData);
        $validator->after(function($validator) use ($option,$optionData,$user,$request) {
            if (!$option) {
                $validator->errors()->add(0, '未找到有效期权合约!');
            }
            if(!$optionData || $optionData['last_price']<=0 || $optionData['buy_price']<=0 || $optionData['sell_price']<=0){
                $validator->errors()->add(0, '休市期间，如有疑问请联系客服!');
            }

            //判断是否休市
            
            $optionDate = date('Ymd',strtotime($optionData['date_time']));
            //echo $optionDate;
            if(date('Ymd')!=$optionDate){
                $validator->errors()->add(0, '休市期间，如有疑问请联系客服!');
            }

            //判断是否是在交易时间
            $times = $option->times;
            $times = explode(',',$times);
            $timesWhere = false;
            foreach($times as $k=>$time){
                list($start,$end) = explode('-',$time);
                if($start>=$end){
                    if(date("w")!=6){
                        if(date('H:i')>=$start || date('H:i',time()+$request->times)<=$end){
                            $timesWhere = true;
                            break;return;
                        }
                    }else{
                        if(date('H:i',time()+$request->times)<=$end){
                            $timesWhere = true;
                            break;return;
                        }
                    }
                    
                }else{
                    if(date('H:i')>=$start && date('H:i',time()+$request->times)<=$end){
                        $timesWhere = true;
                        break;return;
                    }else{
                        
                    }
                }
            }

            if(!$timesWhere){
                $validator->errors()->add(0, '不在交易时段，如有疑问请联系客服!');
            }

            //

            
            //判断余额是否足够
            if($user->balance<$request['amount']){
                $validator->errors()->add(0, '余额不足，请先充值!');
            }

        });

        //判断是否休市


        //
        
        if ($validator->fails()) {
            $msg=[];
            $messages  = $validator->errors();
            foreach ($messages ->all() as $message) {
                //
                $msg[0] = $message;
            }
            //$msg->status = 0;
            //return response()->json(['status'=>0,'msg'=>$msg->first()], 200);
            return response()->json(['status'=>0,'msg'=>$msg], 200);
        }


        DB::beginTransaction();
        try{ 
            //订单编码
            $orderno = date('YmdHis').rand(1000,9999);
            $note = $option->name.'('.$option->code.')下单，订单号:'.$orderno;
            $result = $this->user->modifyBalance($user->id,-$request['amount'],3,$note);
            //return response()->json(['status'=>1,'order'=>$result], 200);
            if($result['status']){
                //return response()->json(['status'=>0,'msg'=>['扣款失败']], 200);
                $order = Order::create([
                    'option_id'=>$request['option_id'],
                    'orderno'=>$orderno,
                    'user_id'=>$user->id,
                    'symbol'=>$option['code'],
                    'amount'=>$request['amount'],
                    'pays'=>$request['amount'],
                    'times'=>$request['times'],
                    'direction'=>$request['direction'],
                    'buy_point'=>$request['buy_point'],
                    'rate'=>$request['yield_rate'],
                    'close_time'=>time()+$request['times']
                ]);
                if($order){

                    //判断是否有上级
                    //$count = UserRelationship::where('subordinateid','=',$user->id)->where('level','>',0)->count();
                    $parents = null;
                    if($user->parent_id){
                        //$parent=$user->parent()->get()->first();
                        $parents=$user->ancestors()->get()->all();
                    }
                    //var_dump($parents);
                    if(!empty($parents)){
                        //dd($parent->mobile);
                        //判断上级是否有代理商
                        
                        //var_dump($maker->superior());exit;
                        $commission_rates=[];
                        //获取分佣比例，逗号分隔
                        // if($makerRelationship){
                          
                        //     $maker =$this->user->find($makerRelationship->superiorid);
                        //     $commission_rates = explode(',',$maker->commission_rate);
                        // }

                        if(empty($commission_rates)){
                            $commission_rates = Config::get('system.commission_rate');
                        }
                        //var_dump($commission_rates);
                        foreach($commission_rates as $k=>$rate){
                            //echo $k;
                            if($k>=count($parents)){
                                break;return;
                            }
                            $parents = array_reverse($parents);
                            $parent = $parents[$k];
                            //var_dump($agent);
                            //var_dump($agent);
                            if(!empty($parent) && $parent->is_agent){
                                $commission = $request['amount']*$rate;
                                Commission::create([
                                    'order_user_id'=>$user->id,
                                    'commission_user_id'=>$parent->id,
                                    'orderno'=>$orderno,                           
                                    'amount'=>$request['amount'],
                                    'commission'=>$commission,
                                    'commission_user_level'=>$k+1,
                                    'note'=>'用户'.$user->name.'('.$user->mobile.')下单佣金'
                                ]);
                            }
                            
                        }
                                                    
                    }
                    //$user = User::find($user->id);
                    $return =  response()->json(['status'=>1,'order'=>$order,'user'=>$user], 200);
                }else{
                    $return = response()->json(['status'=>0,'msg'=>['下单失败']], 200);
                }
            }else{
                $return = response()->json(['status'=>0,'msg'=>[$result['msg']]], 200);
            }
            
            
            //中间逻辑代码 
            DB::commit(); 
            return $return;
        }catch (\Exception $e) { 
            //接收异常处理并回滚 
            var_dump($e);
            DB::rollBack(); 
            return response()->json(['status'=>0,'msg'=>['系统异常，下单失败']], 200);
        }

        
        
       //return response()->json(['status'=>1,'order'=>1], 200);
        

    }

    /**
     * [position 持仓订单]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function position(Request $request,$option_id){
        $user = $request->user();
        //获取持仓数据
        $orders = Order::where('user_id','=',$user->id)
                ->where('option_id','=',$option_id)
                ->where('close_time','>',time())
                ->where('status','=','0')
                ->get();
        foreach($orders as $k=>$order){
            $countdown = $order->close_time-time();
            $order->countdown = $countdown;
            $option_name = $order->option->name;
            $order->option_name = $option_name;
        }
        return response()->json($orders);
    }

    /**
     * [settlement 结算订单]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function settlement(Request $request,$option_id){
        $user = $request->user();
        //获取持仓数据
        $orders = Order::where('user_id','=',$user->id)
                ->where('option_id','=',$option_id)
                ->where('status','>','0')
                ->orderBy('id','desc')
                ->paginate(5);
        foreach($orders as $k=>$order){
            $option_name = $order->option->name;
            $order->option_name = $option_name;
            $order->close_time = date('Y-m-d H:i:s',$order->close_time);
        }
        $user = User::find($user->id);
        return response()->json(['orders'=>$orders,'user'=>$user]);
    }

}